package datasources.flipdatasource;

import java.io.UnsupportedEncodingException;
import java.util.Vector;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import bookhive.datastructures.datasource.DataItem;

public class FlipDataQueryContentHandler extends DefaultHandler {
	
	private static final String ENCODING = "UTF-8";
	private Vector<DataItem> records;
	private boolean recording;
	
	private long currentid = 0;
	private String currenttype;
	private String currentdata;
	
	private StringBuffer buffer = new StringBuffer();
	
	public FlipDataQueryContentHandler(){
		records = new Vector<DataItem>();
		recording = false;
	}
	
	public Vector<DataItem> getRecords(){
		return records;
	}

	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
		
		if(recording){
			String a = new String(arg0, arg1, arg2);
			buffer = buffer.append(a);//java.net.URLDecoder.decode(a, "UTF-8");
		}
		
	}

	
	public void endElement(String arg0, String arg1, String arg2) throws SAXException {

		if(!recording) return;
		
		String string = "";
		try {
			string = java.net.URLDecoder.decode(buffer.toString(), ENCODING);
		} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
		buffer = new StringBuffer();
		if(arg2.equals("id"))
				currentid = Long.parseLong(string);
		else if(arg2.equals("type"))
			currenttype = string;
		else if(arg2.equals("data"))
			currentdata = string;
		else if(arg2.equals("resultSet"))
			recording = false;
		else if (arg2.equals("record")){
			DataItem di = new DataItem();
			di.id = currentid;
			di.type = currenttype;			
			di.data = currentdata;
			records.add(di);

		}

	}

	
	public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
		if(arg2.equals("resultSet"))
			recording = true;
		else if(arg2.equals("record")){
			currentid = 0;
			currenttype = null;
			currentdata = null;
		}
	}

	
	
}
